// 默认选择的消息类型、消息状态、工程师id(默认是全部门)、群id、群名、消息id
let options = {
    type: "problem",
    status: "0",
    engineer_id: "",
    cp_id: "",
    cp_name: "",
    hq: "",
    time: "0",
    endTime: '0'
}


let engineerName = "[[${engineerName}]]"

if (engineerName !== '' || engineerName !== null) {
    options.engineer_id = engineerName;
} else {
    options.engineer_id = 'all_engineer'
}


let tempFormStatus = {}

//群名列表
let group_list = document.getElementById("group_list")

//<button type="button"  onclick="selMsgByGroup(id,value,'待处理数量')" class="layui-btn layui-btn-normal layui-btn-fluid" id='cp_id' value='群名'>cp_name</button>
//<span class="layui-badge layui-bg-cyan">数量</span>
// 群名列表按钮所需单元格元素
let div_group_msg = "<tr>\n" +
    "                    <td><button type=\"button\"  onclick=\"selMsgByGroup(id,value,'待处理数量')\" class=\"layui-btn layui-btn-normal layui-btn-fluid\" id='cp_id' value='群名'>cp_name</button></td>\n" +
    "                </tr>"
//解决按钮所需元素
let button_update_msg_status = "<button type=\"button\"  onclick=\"update_message_status('msg_id','engineer')\" class=\"layui-btn-sm  layui-border-black layui-btn-fluid\" >关闭</button>"
let laypage;
let layer;

// {"engineer_name":"","group_name":"","type":"problem","status":"all"}
layui.use('form', function () {
    const form = layui.form;
    form.on('select(formDemo)', function (data) {

        options.engineer_id = data.value
        // console.log('选择的员工id' + options.toString()); //得到被选中的值
        ask_all_group_message(options)
        ask_all_message(options)
    });


});
layui.use(['laypage', 'layer'], function () {
    laypage = layui.laypage
    layer = layui.layer;
    //完整功能
    laypage.render({
        elem: 'tFoot'
        , count: 100
        , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
        , jump: function (obj) {
            // console.log(obj)
        }
    });
})
layui.use('laydate', function () {
    const layDate = layui.laydate;

    //日期时间范围
    layDate.render({
        elem: '#test10'
        , type: 'datetime'
        , range: true
        , trigger: 'mousedown'
        , done: function (value) {
            let time = value.substring(0, 19)
            let endTime = value.substring(22)
            // console.log("value" + value)
            if (value !== '') {
                options.time = Date.parse((new Date(time).toString())) / 1000
                options.endTime = Date.parse((new Date(endTime).toString())) / 1000
            }

            // console.log(options)
            ask_all_group_message(options)

            ask_all_message(options)
        }
    });
});

//修改选中的员工
function changeEngineer(name) {
    $("#all_engineer").val(name);
    options.engineer_id = name
    // console.log('选择的员工id' + options.toString()); //得到被选中的值
    ask_all_group_message(options)
    ask_all_message(options)
    //渲染下拉框
    layui.use('form', function () {
        const form = layui.form;
        form.render("select");
    });
}


function BTNNameEngineer(name) {

    changeEngineer(name)
    console.log(name)
}

function addTbody(data, ElementId) {

    let tbModel = '<tr>\n' +
        '                    <td>\n' +
        '                        <button  class="layui-btn   layui-btn-danger layui-btn-fluid layui-btn-sm"\n' +
        '                                onclick="BTNNameEngineer(\'engineerName\')">engineer_name\n' +
        '                        </button>\n' +
        '                    </td>\n' +
        '                    <td style="text-align: center ">\n' +
        '                      problemNum  \n' +
        '                    </td>\n' +
        '                </tr>'
    let tbodyNeedAddProblemStatus = document.getElementById(ElementId)
    let temp = ''
    tbodyNeedAddProblemStatus.innerHTML = ''
    console.log(data)
    for (let i = 0; i < data.length; i++) {
        temp = tbModel.replace('engineerName', data[i]['engineer'])
        temp = temp.replace('engineer_name', data[i]['engineer'])
        if (typeof (data[i]['problemNum']) !== "undefined") {
            temp = temp.replace('problemNum', data[i]['problemNum'])
        } else if (typeof (data[i]['needToReplyNum']) !== "undefined") {
            temp = temp.replace('problemNum', data[i]['needToReplyNum'])
        }
        tbodyNeedAddProblemStatus.innerHTML += temp
    }


}

function ask_allNeedAddProblemStatus_engineer() {
    $.ajax({
        url: "/selEngineerNeedAddProblemStatusCount"
        , type: "get"
        , dataType: "json"
        , contentType: "application/json;charset=utf-8"
        , success: function (data) {
            addTbody(data, 'tbodyNeedAddProblemStatus')
        }
    })
}

//菜单栏事件，获取选择的消息类型与消息状态
layui.use('dropdown', function () {
    let dropdown = layui.dropdown;

    //菜单点击事件，其中 docDemoMenu1 对应的是菜单结构上的 id 指
    dropdown.on('click(docDemoMenu1)', function (data) {
        options.type = data.type
        options.status = data.status
        document.getElementById("message_list").innerHTML = ''
        ask_all_group_message(options)
        ask_all_message(options)
        document.getElementById('thGroupName').innerText = '群名'

        let titleNeedToReply = document.getElementById('titleNeedToReply')

        if (options.status === 0) {
            if (options.type === 'problem') {

                titleNeedToReply.innerHTML = '要添加问题状态的数量'
                ask_allNeedAddProblemStatus_engineer()
            } else if (options.type === 'message') {
                titleNeedToReply.innerHTML = '超时未响应的数量'
                ask_allNeedReplyMessage()
            } else {
            }
        }
    });
});

function ask_allNeedReplyMessage() {
    // console.log('超时未响应的数量')
    $.ajax({
        url: "/selEngineerNeedToReplyNum"
        , type: "get"
        , dataType: "json"
        , contentType: "application/json;charset=utf-8"
        , success: function (data) {
            addTbody(data, "tbodyNeedAddProblemStatus")
        }
    })
}

function ask_all_message(options) {
    $.ajax({
        url: "/ask_all_message"
        , data: {
            data: JSON.stringify(options)
        }
        , type: "get"
        , dataType: "json"
        , contentType: "application/json;charset=utf-8"
        , success: function (data) {
            console.log(data)
            add_msg_list(data)
        }
    })
}

let form_status =
    `<div class="layui-tab" lay-filter="demo" lay-allowclose="true">
        <ul class="layui-tab-title">
            <li class="layui-this" lay-id="11">添加状态</li>
            <li lay-id="22">补充问题</li>
            <li lay-id="33">分配给其他人</li>

        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show"><table class="layui-table" style="display: none">
                    <colgroup>
                        <col style="width:300px">
                        <col style="width:100px">
                        <col style="width:100px">
                        <col>
                    </colgroup>
                    <thead>
                    <tr>
                        <th>状态</th>
                        <th>人员</th>
                        <th>时间</th>
                    </tr>
                    </thead>
                    <tbody id="tb_problem_status">tbProblemStatus

                    </tbody>
                </table>
                <textarea placeholder="请输入内容" class="layui-textarea"
                          id='addMsgStatusAreaId'></textarea>
                <button type="button" class="layui-btn layui-btn-danger" onclick="add_msg_status_content('AMSID')">更新状态</button>
            </div>
            <div class="layui-tab-item">
                <textarea placeholder="请输入内容" class="layui-textarea" id='updateTextAreaId' style='height: auto'>changeProblemContent</textarea>
                <button type="button" class="layui-btn layui-btn-danger" onclick="update_message_content('tAId')">提交修改
                </button>
            </div>
            <div class="layui-tab-item">
                changeEngineer
            </div>
        </div>
    </div>`

//添加问题当前状态
function add_msg_status_content(add_msg_status_content_id) {
    let addMsgStatusContentId = document.getElementById(add_msg_status_content_id)
    if (addMsgStatusContentId.value !== null && addMsgStatusContentId.value !== '') {
        let msg = {}
        msg.hq = add_msg_status_content_id.substring(3)

        msg.msgStatusContentValue = addMsgStatusContentId.value
        // msg.engineer = engineer_name

        $.ajax({
            url: "/add_problem_status"
            , data: {data: JSON.stringify(msg)}
            , type: "get"
            , dataType: "json"
            , contentType: "application/json;charset=utf-8"
            , success: function () {

                layui.use('layer', function () {
                    layer.closeAll()
                });
                add_msg_status(add_msg_status_content_id.substring(3), 'engineer')
                // updateProblemStatusTable(add_msg_status_content_id.substring(3))
            }
        })
    }

}

//修改问题内容
function update_message_content(msgId) {
    let updateTextArea = document.getElementById(msgId)
    let data = {}
    data.hq = msgId.substring(7)
    data['text'] = updateTextArea.value
    $.ajax({
        url: "/change_problem"
        , data: {
            data: JSON.stringify(data)
        }
        , type: "get"
        , dataType: "json"
        , contentType: "application/json;charset=utf-8"
        , success: function () {
            layui.use('layer', function () {
                layer.closeAll()
            });

            add_msg_status(msgId.substring(7), 'engineer')

        }
    })


}

function add_msg_status(msg_id, engineer) {
    updateProblemStatusTable(msg_id)
    $.ajax({
        url: "/selMsgByHq"
        , data: {
            hq: msg_id
        }
        , type: "get"
        , dataType: "json"
        , contentType: "application/json;charset=utf-8"
        , success: function (data) {

            // console.log(msg_by_hq)

            let msg_by_hq = data["selMsgByHq"]
            let tb_problem_status_content = data["problemStatusByHq"]

            let temp = '';
            for (let i = 0; i < tb_problem_status_content.length; i++) {
                temp += '<tr><td>' + tb_problem_status_content[i]['statusContent']
                    + '</td><td>' + tb_problem_status_content[i]['engineer']
                    + '</td><td>' + tb_problem_status_content[i]['timeFormat']
                    + '</td></tr>'
            }

            // console.log(temp)
            // console.log(msg_by_hq, tb_problem_status_content)

            tempFormStatus = form_status.replace('changeProblemContent', msg_by_hq.text)
            tempFormStatus = tempFormStatus.replace('changeEngineer', msg_by_hq.engineer)
            tempFormStatus = tempFormStatus.replace('tAId', "update_" + msg_by_hq.hq)
            tempFormStatus = tempFormStatus.replace('updateTextAreaId', "update_" + msg_by_hq.hq)
            tempFormStatus = tempFormStatus.replace('AMSID', "add" + msg_by_hq.hq)
            tempFormStatus = tempFormStatus.replace('addMsgStatusAreaId', "add" + msg_by_hq.hq)


            // console.log(msg_by_hq["msgStatus"])


            if (temp !== "" && temp != null) {
                tempFormStatus = tempFormStatus.replace('display: none', '')

                // tempFormStatus = tempFormStatus.replace('tbProblemStatus', tableUpdateProblemStatus)
                tempFormStatus = tempFormStatus.replace('tbProblemStatus', temp)
                // tdParsing(msg_by_hq["msgStatus"])
            } else {

                tempFormStatus = tempFormStatus.replace('tbProblemStatus', "")
            }

            layui.use('layer', function () {
                layer.open({
                    type: 1,
                    title: false,
                    scrollbar: false,
                    content: tempFormStatus,
                    area: ['80%', '60%']
                });


                layui.use('form', function () {
                    const form = layui.form;
                    //表单取值
                    layui.$('#LAY-component-form-eval').on('click', function () {
                        let data = form.val('solution_input');
                        if (data['solution'] !== "") {
                            data['engineer'] = engineer
                            data['hq'] = msg_id
                            data['type'] = options.type
                            data['status'] = options.status
                            ajax_update_status(data)
                            parent.layer.closeAll()
                            layer.msg('已经解决啦');
                            document.getElementById(msg_id).innerHTML = ''
                            //关闭悬浮框
                        } else {
                            layer.msg('你还没有输入解决方案哦');
                        }

                    });

                });
            })
        }
    })
}

let tableUpdateProblemStatus = ''

function get_tableUpdateProblemStatus(data) {
    let tempTable = ''
    for (let i = 0; i < data.length; i++) {
        tempTable = tempTable + '<tr>'
        tempTable = tempTable + '<td>' + data[i]['statusContent'] + '</td>'
        tempTable = tempTable + '<td>' + data[i]['engineer'] + '</td>'
        tempTable = tempTable + '<td>' + data[i]['timeFormat'] + '</td>'
        tempTable = tempTable + '</tr>'
    }
    tableUpdateProblemStatus = tempTable
}

function updateProblemStatusTable(hq) {
    $.ajax({
        url: "/problemStatusByHq"
        , data: {
            hq: hq
        }
        , type: "get"
        , dataType: "json"
        , contentType: "application/json;charset=utf-8"
        , success: function (data) {
            get_tableUpdateProblemStatus(data)
        }
    })
}


let form_solution = "<form class='layui-form' lay-filter=\"solution_input\"> \n" +
    "      <textarea placeholder=\"请输入内容\" class=\"layui-textarea\" name=\"solution\"></textarea>\n" +
    "    <button type=\"button\" class=\"layui-btn layui-btn-fluid\" id=\"LAY-component-form-eval\">提交</button></form>"


function update_problem_status(msg_id, engineer) {

    layui.use('layer', function () {
        layer.open({
            type: 1,
            title: "填写你的解决方案",
            scrollbar: false,
            content: form_solution,
            area: ['420px', '195px']
        });

        layui.use('form', function () {
            const form = layui.form;
            //表单取值
            layui.$('#LAY-component-form-eval').on('click', function () {
                let data = form.val('solution_input');
                if (data['solution'] !== "") {
                    data['engineer'] = engineer
                    data['hq'] = msg_id
                    data['type'] = options.type
                    data['status'] = options.status
                    ajax_update_status(data)
                    parent.layer.closeAll()
                    layer.msg('已经解决啦');
                    document.getElementById(msg_id).innerHTML = ''
                    //关闭悬浮框
                } else {
                    layer.msg('你还没有输入解决方案哦');
                }

            });

        });
    })
}

//ajax请求修改问题状态
function ajax_update_status(options) {
    let return_data = 0
    $.ajax({
        url: "/update_msg_status"
        , data: {
            data: JSON.stringify(options)
        }
        , type: "get"
        , dataType: "json"
        , contentType: "application/json;charset=utf-8"
        , success: function (data) {
            // console.log(data)
            return_data = data
        }
    })
    return return_data
}


function update_message_status(msg_id, engineer) {

    let data = {}
    data['engineer'] = engineer
    data['hq'] = msg_id
    data['type'] = options.type
    data['status'] = options.status

    ajax_update_status(data)
    layer.msg('已经修改成功');
    document.getElementById(msg_id).innerHTML = ''
}

function compare(property) {
    return function (obj1, obj2) {
        const value1 = obj1[property];
        const value2 = obj2[property];
        return value1 - value2;     // 升序
    }
}

function ask_all_group_message(data) {
    $.ajax({
        url: "/all_group_message"
        , data: {
            data: JSON.stringify(data)
        }
        , type: "get"
        , dataType: "json"
        , contentType: "application/json;charset=utf-8"
        , success: function (data) {
            data.sort(compare("time"))
            add_group_info(data)
            // console.log(data)
        }
    })
}

let div_message_list = "<tr id='hq_id'>\n" +
    "                        <td > text</td>\n" +
    "                        <td>engineer</td>\n" +
    "                        <td>time</td>\n" +
    "                        <td>button</td>\n" +
    "                    </tr>"

function addZero(m) {
    return m < 10 ? '0' + m : m;
}

function selMsgByGroup(id, cp_name, count_msg) {
    options.hq = count_msg
    options.cp_id = id
    options.cp_name = cp_name

    document.getElementById('thGroupName').innerText = cp_name
    // console.log(JSON.stringify(options))

    $.ajax({
        url: "/msg_byGroupId"
        , data: {
            data: JSON.stringify(options)
        }
        , type: "get"
        , dataType: "json"
        , contentType: "application/json;charset=utf-8"
        , success: function (data) {
            console.log(data)
            add_msg_list(data)
        }
    })
}

function timeTemp(time_temp) {
    let date = new Date(time_temp * 1000)
    let Y = date.getFullYear() + '-';
    let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    let D = date.getDate() + ' ';
    let h = date.getHours() + ':';
    let m = date.getMinutes() + ':';
    let s = date.getSeconds();
    return Y.substr(2) + addZero(M) + addZero(D) + addZero(h) + addZero(m) + addZero(s)
}

//向问题列表添加具体问题
function add_msg_list(data) {

    let temp_message_list

    let messageList = document.getElementById("message_list")
    messageList.innerHTML = ''
    for (let i = 0; i < data.length; i++) {

        let time_temp;
        temp_message_list = div_message_list.replace("text", data[i]['text'])
        temp_message_list = temp_message_list.replace("engineer", data[i]['engineer'])


        time_temp = timeTemp(data[i]['time'])

        temp_message_list = temp_message_list.replace("time", data[i]['admin'])
        temp_message_list = temp_message_list.replace("hq_id", data[i]['hq'])

        if (data[i]['status'] === 0) {
            //按钮
            let temp_button_update_msg_status = button_update_msg_status.replace("msg_id", data[i]['hq'])
            let temp_button_add_msg_status = button_update_msg_status.replace("msg_id", data[i]['hq'])

            temp_button_add_msg_status = temp_button_add_msg_status.replace("engineer", data[i]['engineer'])
            temp_button_add_msg_status = temp_button_add_msg_status.replace("trOnClick", 'update_message_status')
            temp_button_update_msg_status = temp_button_update_msg_status.replace("engineer", data[i]['engineer'])

            // temp_button_update_msg_status = temp_button_update_msg_status.replace("engineer", data[i])
            // options.engineer_id=data[i]['engineer']

            if (data[i]['type'] === 'message') {
                temp_button_update_msg_status = temp_button_update_msg_status.replace("update_message_status", 'update_message_status')
            } else {
                temp_button_update_msg_status = temp_button_update_msg_status.replace("update_message_status", 'update_problem_status')
                temp_button_add_msg_status = temp_button_add_msg_status.replace("update_message_status", 'add_msg_status')
                temp_button_add_msg_status = temp_button_add_msg_status.replace("关闭", '编辑')
                temp_button_update_msg_status += temp_button_add_msg_status

            }
            temp_message_list = temp_message_list.replace("button", temp_button_update_msg_status)
            // temp_message_list = temp_message_list.replace("button", button_update_msg_status.replace("engineer", data[i]['engineer']))

        } else if (data[i]['status'] === 1) {
            if (data[i]['type'] === 'message') {
                temp_message_list = temp_message_list.replace("button", "<br>【" + data[i]['processor'] + "】")

            } else {
                //解决人
                temp_message_list = temp_message_list.replace("button", data[i]['solution'] + "<br>【" + data[i]['processor'] + "】")
            }

        }
        messageList.innerHTML += temp_message_list
    }
}

function add_group_info(data) {
    let div_group_msg_temp;
    group_list.innerHTML = ""
    for (let i = 0; i < data.length; i++) {
        div_group_msg_temp = div_group_msg.replace("cp_name", data[i]["cpName"] + "【" + data[i]["hq"] + "】")
        div_group_msg_temp = div_group_msg_temp.replace("群名", data[i]["cpName"])
        div_group_msg_temp = div_group_msg_temp.replace("cp_id", data[i]["cpId"])
        // div_group_msg_temp = div_group_msg_temp.replace("数量", "数量" + data[i]["hq"])
        div_group_msg_temp = div_group_msg_temp.replace("待处理数量", data[i]["hq"])
        group_list.innerHTML = group_list.innerHTML + div_group_msg_temp
    }


}


let problemOn = document.getElementById('problemOn')
// console.log(problemOn)
problemOn.click()
ask_all_group_message(options)
ask_all_message(options)
ask_allNeedAddProblemStatus_engineer()
